//
//  HTComposeViewController.swift
//  mySinaBlog
//
//  Created by whtapple on 4/2/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit

class HTComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNavigationBar()
        setupTextView()
        setupToolBar()
    }
     //MARK -使键盘在 view出现后，就跟着出现
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }
    //MARK -创建 textview
    private func setupTextView(){
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        textView.backgroundColor = UIColor.purpleColor()
        
        //注册监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewchange", name: UITextViewTextDidChangeNotification, object: textView)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeAction:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //监听发送按钮是否可以用方法
    func textViewchange(){
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    ///监听文本改变回调
    //    name = UIKeyboardWillChangeFrameNotification; userInfo = {
    //    UIKeyboardAnimationCurveUserInfoKey = 7;
    //    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    //    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
    //    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
    //    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
    //    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
    //    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
    //    UIKeyboardIsLocalUserInfoKey = 1;
    //toolbar 跟随键盘移动回调
    func keyboardWillChangeAction(notification: NSNotification){
    Xprint(msg: "notification=\(notification)")
        //拿到动画时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        //拿到动画结束时的 frame
        let endframe = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //算出移动的距离
        let margin = -(UIScreen.height - endframe.origin.y)
        //更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(margin)
        }
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK -创建 toolbar
    //设置 toolbar
    private func setupToolBar(){
        view.addSubview(toolbar)
        //约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        //保存信息数组
        let btnData = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        //新建一个空的数组来保存 items
        toolbar.items = [UIBarButtonItem]()
        var index = 0
        for dict in btnData{
            let image = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(imageString: image, target: self, selector: Selector(action))
            let button = item.customView
            button?.tag = index
            index++
            toolbar.items?.append(item)
            toolbar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil))
        }
        toolbar.items?.removeLast()
    }
    //MARK -完成 toolbar的回调
    func picture(){
        Xprint(msg: "picture")
    }
    func trend(){
        Xprint(msg: "trend")
    }
    func mention(){
        Xprint(msg: "mention")
    }
    func emoticon(){
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? keyboardView : nil
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
                self.textView.becomeFirstResponder()
        }
    }
    func add(){
        Xprint(msg: "add")
    }
    //MARK -导航栏设置
    //设置导航栏
    private func setupNavigationBar(){
        //左边取消按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickCancelBtn")
        //右边发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickSendlBtn")
        navigationItem.rightBarButtonItem?.enabled = false
        setupTitleView()
        
    }
    private func setupTitleView(){
        let prifix = "发微博"
        if let name = HTUserAccountViewModel.sharedInstance.userAccount?.screen_name{
            //创建一个label, 并设置属性
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(13)
            label.numberOfLines = 0
            //创建一个文本
            let text = prifix + "\n" + name
            //创建一个可变属性字符串
            let attr = NSMutableAttributedString(string: text)
            //要设置属性的字符创的范围
            let range:NSRange = (text as NSString).rangeOfString(name)
            //设置字符串的属性
            attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(),NSFontAttributeName : UIFont.systemFontOfSize(11)], range: range)
            //添加到 label
            label.attributedText = attr
            label.sizeToFit()
            //添加到标题 VIEW
            self.navigationItem.titleView = label
        }else{
            //如果没有名字的话，就直接返回一个 title
            self.navigationItem.title = prifix
        }
        
    }
    //MARK: -按钮回调
    //取消按钮
    @objc func didClickCancelBtn(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送按钮
    @objc func didClickSendlBtn(){
        Xprint(msg: "发送")
    }
    //懒加载数据
    private lazy var toolbar: UIToolbar = UIToolbar()
    //懒加载数据
    private lazy var textView: HTPlaceholderTextView = {
        //创建一个先
        let textView = HTPlaceholderTextView()
        //设置字体
        textView.font = UIFont.systemFontOfSize(18)
        //设置字体颜色
        textView.textColor = UIColor.blackColor()
        //垂直方向弹簧
        textView.alwaysBounceVertical = true
        //拖拽键盘消失
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
//        textView.placefont = UIFont.systemFontOfSize(40)
//        textView.placeholderText = "mylove"
        return textView
    }()
    //懒加载数据
    private lazy var keyboardView: HTkeyboardEmotionView = {
        let keyboard = HTkeyboardEmotionView()
        keyboard.textView = self.textView
        return keyboard
    }()
}
